<?php
namespace app\index\controller;
use think\Controller;
use think\Session;
class Index extends Controller
{
    private $client;
    public function _initialize()
    {
        if($this->client==null)
        {
            $this->client = new \swoole_client(SWOOLE_SOCK_TCP);
            if (!$this->client->connect('127.0.0.1', 9501, -1))
            {
                exit("connect failed. Error: {$this->client->errCode}\n");
            }
        }
        Session::init([
            'prefix'         => 'mishi',
            'type'           => '',
            'auto_start'     => true,
        ]);
    }
    public function index()
    {
        if(!Session::has('name'))
        {
            return redirect('Index/login')->remember();
        }
        if($this->client!=null&&$this->client->isConnected())
        {
            $data=['function'=>'get_led_status','param'=>['1']];
            $this->client->send(json_encode($data)."\n");
            $re=json_decode($this->client->recv(),true);
            if($re['code']==0)
            {
                $this->assign('led_status', $re['data']);
            }
            else
            {
                return "错误信息".$re['msg'];
            }
            return $this->fetch();
        }
        else
        {
            return "未能连接到Python";
        }
    }
    public function switch_led()
    {
        if($this->client!=null&&$this->client->isConnected())
        {
            $data=['function'=>'switch_led','param'=>[]];
            $this->client->send(json_encode($data)."\n");
            $re=json_decode($this->client->recv(),true);
            if($re['code']!=0)
            {
                return "错误信息".$re['msg'];
            }
            else
            {
                $this->redirect('/',302);
            }
        }
    }
    public function login()
    {
        if(Session::has('name'))
        {
            return redirect('/');
        }
        $this->assign('remurl',redirect()->restore());
        return $this->fetch();
    }
    public function dologin($username = '',$password = '')
    {
        if(Session::has('name'))
        {
            return redirect('/');
        }
        if($username == '')
        {
            $this->error('用户名不能为空');
        }
        if($password == '')
        {
            $this->error('密码不能为空');
        }
        $re=cUrl('http://ant-shell.com/api/verify?username='.$username.'&psswd='.$password);
        if($re['code']==200)
        {
            Session::set('name',$username);
            $this->success('登录成功', '/','',1);
        }
        else
        {
            $this->error('用户名或密码错误','',1);
        }
    }
    public function logout()
    {
        if(!Session::has('name'))
        {
            return redirect('Index/login')->remember();
        }
        Session::delete('name');
        $this->success('登出成功', '/','',1);
    }
}
